<?php


namespace app\api\controller\keyan;

use app\common\controller\Api;
use app\common\model\File;
use app\common\model\ProjectFunds;
use app\common\model\ProjectSource;
use app\common\model\ProjectType;
use think\Db;
use Exception;
use think\exception\ValidateException;
use think\exception\PDOException;


/**
 * 科研项目
 */
class project extends Api
{
    /**
     * 列表
     */
    public function list()
    {
        $model = new \app\common\model\Project();
        $pageNum = input('pageNum', 1);
        $pageSize = input('pageSize', 10);
        $name = input('name');
        $source_id = input('source_id');
        $type_id = input('type_id');
        $where_sql = [];
        $where_sql['user_id'] = $this->auth->id;
        if ($name) {
            $where_sql['name'] = ['like', "%$name%"];
        }
        if ($source_id) {
            $where_sql['source_id'] = $source_id;
        }
        if ($type_id) {
            $where_sql['type_id'] = $type_id;
        }
        $data = $model->where($where_sql)->order(['top'=>'desc', 'id'=>'desc'])->paginate(['page'=>$pageNum,'list_rows'=>$pageSize]);
        $this->success('', $data);
    }

    /**
     * 项目来源/类型 列表
     */
    public function source_type()
    {
        $type = input('type', 1);
        if ($type == 1) {
            $model = new ProjectSource();
        }  else {
            $model = new ProjectType();
        }

        $list = $model->select();
        $this->success('', $list);
    }

    /**
     * 添加
     *
     * @ApiMethod (POST)
     */
    public function add()
    {
        $param = input('post.');
        if (!$param) {
            $this->error('参数不正确');
        }
        $user_id = $this->auth->id;
        $param['user_id'] = $user_id;
        $project_funds = $this->request->post('project_funds/a');
        Db::startTrans();
        try {
            $projectModel = new \app\common\model\Project();
            $projectModel->data($param);
            $projectModel->allowField(true)->save();
            $project_id = $projectModel->id;

            //科研经费
            if ($project_funds) {
                if (!is_array($project_funds)) {
                    $project_funds = json_decode($project_funds, true);
                }
                foreach ($project_funds as &$v) {
                    if (!is_array($v)) {
                        $v = json_decode($v, true);
                    }
                    $v['project_id'] = $project_id;
                }
                $fundsModel = new ProjectFunds();
                $fundsModel->allowField(true)->saveAll($project_funds);
            }

            //附件
            if (isset($param['file']) && $param['file']) {
                File::where('id', 'in', $param['file'])->update(['pid'=>$project_id,'type'=>1,'user_id'=>$user_id]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('保存成功');

    }

    /**
     * 单个科研项目的信息
     */
    public function info()
    {
        $id = input('id');
        if (!$id) {
            $this->error('id不能为空');
        }
        $model = new \app\common\model\Project();
        $where_sql['id'] = $id;
        $user_id = $this->auth->id;
        $where_sql['user_id'] = $user_id;
        $info = $model->where($where_sql)->find();
        if ($info) {
            $info['file'] = File::where(['pid'=>$id,'type'=>1,'user_id'=>$user_id])->field('id,name,url')->select();
            $info['project_funds'] = ProjectFunds::where('project_id', $id)->field('project_id', true)->select();
        }
        $this->success('', $info);
    }

    /**
     * 编辑
     *
     * @ApiMethod (POST)
     */
    public function edit()
    {
        $projectModel = new \app\common\model\Project();
        $param = input('post.');
        $project_funds = $this->request->post('project_funds/a');
        $user_id = $this->auth->id;
        Db::startTrans();
        try {
            $projectModel->allowField(true)->isUpdate(true)->save($param);

            //科研经费
            if ($project_funds) {
                $reserve_id = [];
                foreach ($project_funds as &$v) {
                    if (!is_array($v)) {
                        $v = json_decode($v, true);
                    }
                    if (isset($v['id']) && $v['id']) {
                        $reserve_id[] = $v['id'];
                    }
                    $v['project_id'] = $param['id'];
                }
                $fundsModel = new ProjectFunds();
                $where_funds['project_id'] = $param['id'];
                if ($reserve_id) {
                    $where_funds['id'] = ['not in', $reserve_id];
                }
                $fundsModel->where($where_funds)->delete();
                $fundsModel->allowField(true)->saveAll($project_funds);
            }

            //附件
            if (isset($param['file']) && $param['file']) {
                File::where('id', 'in', $param['file'])->update(['pid'=>$param['id'],'user_id'=>$user_id,'type'=>1]);
                File::where('id', 'not in', $param['file'])->where(['pid'=>$param['id'],'user_id'=>$this->auth->id,'type'=>1])->delete();
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error('修改失败,请重试');
        }

        $this->success('修改成功');
    }

    /**
     * 删除
     *
     * @ApiMethod (POST)
     */
    public function del()
    {
        $id = $this->request->post('id/a');
        if (!$id) {
            $this->error('id不能为空');
        }
        $model = new \app\common\model\Project();
        $where_sql['id'] = ['in', $id];
        $user_id = $this->auth->id;
        $where_sql['user_id'] = $user_id;
        $model->where($where_sql)->delete();
        File::where(['pid'=>['in', $id],'user_id'=>$user_id,'type'=>1])->delete();
        ProjectFunds::whereIn('project_id', $id)->delete();
        $this->success('删除成功');
    }

    /**
     * 设置/取消 代表作
     *
     * @ApiMethod (POST)
     * @param int $id 项目id
     * @param int $type 类型,1=设置,其它的=取消代表作
     */
    public function setTop()
    {
        $id = input('id');
        if (!$id) {
            $this->error('id不能为空');
        }
        $model = new \app\common\model\Project();
        $where_sql['id'] = $id;
        $where_sql['user_id'] = $this->auth->id;
        $type = input('type', 1);
        if ($type == 1) {
            $result = $model->where($where_sql)->update(['top'=>1]);
        } else {
            $result = $model->where($where_sql)->update(['top'=>0]);
        }

        if ($result !== false) {
            $this->success('设置成功');
        } else {
            $this->error('设置失败');
        }
    }

}